package framework;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Transactional(readOnly=true, propagation = Propagation.REQUIRED)
public class GenericDaoImp<E extends BaseObject, ID extends Serializable> implements GenericDao<E, ID>{
	
	private EntityManager entityManager;
	private final Class<E> oClass;
	
	@SuppressWarnings(value = "unchecked")
	public GenericDaoImp() {
		this.oClass = (Class<E>)(((java.lang.reflect.ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
	}
	@Override
	public E atualizar(E object) {
		object.beforeSave();
		object.afterSave();
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void excluir(E object) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public Class<E> getObjectClass() {
		// TODO Auto-generated method stub
		return oClass;
	}
	@Override
	public List<E> listPesq(String query) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	@SuppressWarnings("unchecked")
	public List<E> listPesqParam(String query, Map<String, Object> params) {
		Query q = getEntityManager().createQuery(query);  
        for(String chave : params.keySet()){  
            q.setParameter(chave, params.get(chave));  
        }  
        return q.getResultList();
	}
	@Override
	public List<E> listPesqParam(String query, Map<String, Object> params,
			int max, int atual) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public E pesqParam(String query, Map<String, Object> params) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public E pesquisarPorId(ID id) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public E salvar(E object) {
		getEntityManager().clear();
		object.beforeCreate();
		getEntityManager().persist(object);
		object.afterCreate();
		return object;
	}
	@Override
	public List<E> todos() {
		// TODO Auto-generated method stub
		return null;
	}
	protected EntityManager getEntityManager() {
		return entityManager;
	}

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
}
